import {
	request
} from '../../utils/request.js'
let app = getApp();
// import _ from 'lodash'
Page({

	/**
	 * 页面的初始数据
	 */
	data: {
		cart: [],
		cartNumber: 0,
		selectAllStatus: true,
		totalMoney: 0,
		sumMoney: 0,
		pre: '',
		delPrice: 0,
		checkCart: '',
		cartLength: 1
	},

	/**
	 * 生命周期函数--监听页面加载
	 */
	onLoad: function (options) {
		let objArr = [{ id: 1, name: 2 }, { id: 1, name: 1 }]
		let res3 = this.uniqObjInArray(objArr);
		this.sendRule()

	},

	uniqObjInArray(objarray) {
		let len = objarray.length;
		let tempJson = {};
		let res = [];
		for (let i = 0; i < len; i++) {
			//取出每一个对象
			tempJson[JSON.stringify(objarray[i])] = true;
		}
		let keyItems = Object.keys(tempJson);
		for (let j = 0; j < keyItems.length; j++) {
			res.push(JSON.parse(keyItems[j]));
		}
		return res;
	},
	add(e) { 
		let goodId = e.currentTarget.dataset.goodid
		let number = this.data.cart.find(item => item.id == goodId).number
		let itemFood = this.data.cart.find(item => item.id == goodId)
		itemFood.number = itemFood.number + 1
		request({
			url: `setNum`,
			token: wx.getStorageSync('token'),
			method: 'POST',
			data: {
				productId: goodId,
				number: number + 1
			}
		}).then(res => {
			this.setData({
				cart: this.data.cart
			});
			console.log('添加之后的cart', this.data.cart)
			let allNums = 0
			this.data.cart.forEach(item => {
				allNums = allNums + item.number
			})
			wx.setStorageSync("cartNumber", allNums)

			app.scanCart()
			let totalMoney = 0
			this.data.checkCart.forEach(item => {
				console.log('选择添加', item)
				totalMoney = totalMoney + (item.market_price * item.number)
			})
			this.setData({
				totalMoney: totalMoney.toFixed(2)
			})
			this.activity()
		})
	},
	minus(e) {
		let goodId = e.currentTarget.dataset.goodid
		let number = this.data.cart.find(item => item.id == goodId).number
		let itemFood = this.data.cart.find(item => item.id == goodId)
		itemFood.number = itemFood.number - 1
		if (itemFood.number <= 0) {
			wx.showToast({
				title: '商品数量最少为1哦', //提示的内容,
				icon: 'none',
				duration: 2000, //延迟时间,
				mask: true, //显示透明蒙层，防止触摸穿透,
				success: res => {
					itemFood.number = 1
				}
			});
			return
		}
		request({
			url: `setNum`,
			token: wx.getStorageSync('token'),
			method: 'POST',
			data: {
				productId: goodId,
				number: number - 1
			}
		}).then(res => {
			this.setData({
				cart: this.data.cart
			});
			let allNums = 0
			this.data.cart.forEach(item => {
				allNums = allNums + item.number
			})
			wx.setStorageSync("cartNumber", allNums)
			app.scanCart()
		})
		let totalMoney = 0
		this.data.checkCart.forEach(item => {
			console.log('选择添加', item)
			totalMoney = totalMoney + (item.market_price * item.number)
		})
		this.setData({
			totalMoney: totalMoney.toFixed(2)
		})
		this.activity()
	},
	//删除数据
	delOrder(e) {
		let that = this
		wx.showModal({
			title: '删除',
			content: '确定要删除本产品吗?',
			success(res) {
				if (res.confirm) {
					let goodId = e.currentTarget.dataset.goodid.id
					request({
						url: `setNum`,
						token: wx.getStorageSync('token'),
						method: 'POST',
						data: {
							productId: goodId,
							number: 0
						}
					}).then(res => {
						that.loadData()
					})
				} else if (res.cancel) {
				}


			}
		})
		let totalMoney = 0
		if (that.data.checkCart && that.data.checkCart.length) {
			that.data.checkCart.forEach(item => {
				totalMoney = totalMoney + (item.market_price * item.number)
			})
		}
		that.setData({
			totalMoney: totalMoney.toFixed(2)
		})
	},

	/** 
	 * 删除多个产品
	*/
	delOrderAll() {
		let that = this
		wx.showModal({
			title: '删除',
			content: '确定要删除选中产品吗?',
			success(res) {
				if (res.confirm) {
					that.data.checkCart.forEach(item => {
						request({
							url: `setNum`,
							token: wx.getStorageSync('token'),
							method: 'POST',
							data: {
								productId: item.id,
								number: 0,
								totalMoney: 0

							}
						}).then(res => {
							that.setData({
								cart: ''
							})
							console.log(111111111111111111)

							// wx.switchTab({ url: '/pages/shopCart/shopCart' });


						})
					})
					that.loadData()
				} else if (res.cancel) {

				}
			}
		})
		let totalMoney = 0
		that.data.checkCart.forEach(item => {
			console.log('选择添加', item)
			totalMoney = totalMoney + (item.market_price * item.number)
		})
		that.setData({
			totalMoney: totalMoney.toFixed(2)
		})
	},

	selectItem(e) {
		const index = e.currentTarget.dataset.index;
		console.log('selectAllStatus', this.data.selectAllStatus)
		let cart = this.data.cart;
		const selected = cart[index].selected;
		cart[index].selected = !selected;
		let totalMoney = 0
		let ckallFlag = cart.find(item => item.selected == true)
		console.log('选择的数据', ckallFlag)


		let checkCart = []
		this.data.cart.forEach(item => {
			if (item.selected || item.selected == 'true') {
				checkCart.push(item)
			}
		})

		if (checkCart.length == this.data.cart.length) {
			this.setData({
				selectAllStatus: true,
				cart
			});
		} else {
			this.setData({
				selectAllStatus: false,
				cart
			});
		}


		checkCart.forEach(item => {
			totalMoney = totalMoney + (item.market_price * item.number)
		})
		this.setData({
			checkCart,
			totalMoney: totalMoney.toFixed(2)
		})
		this.activity()
		console.log('选择的所有数据', this.data.checkCart)

	},


	// 默认全选
	selectAllDefault() {
		this.selectAllData(this.data.selectAllStatus)
	},
	// 全选的点击事件
	selectAll() {
		let selectAllStatus = !this.data.selectAllStatus;
		this.selectAllData(selectAllStatus)
	},

	selectAllData(selectAllStatus) {
		let totalMoney = 0

		let cart = this.data.cart;
		for (let i = 0; i < cart.length; i++) {
			cart[i].selected = selectAllStatus;
		}
		console.log('selectAllStatus的值', selectAllStatus)
		if (selectAllStatus) {
			cart.forEach(item => {
				totalMoney = totalMoney + (item.market_price * item.number)
			})
			this.setData({
				selectAllStatus,
				cart,
				checkCart: cart,
				totalMoney: totalMoney.toFixed(2)
			});
		} else {

			this.setData({
				selectAllStatus,
				cart,
				checkCart: '',
				totalMoney: totalMoney.toFixed(2)
			});
		}

		this.activity()
		console.log('全部选中', this.data.checkCart)
	},

	/**
	 * 生命周期函数--监听页面显示
	 */
	onShow: function () {
		this.loadData()

	},

	loadData() {
		let newCar = []
		let allNums = 0
		let type = 1
		this.setData({
			totalMoney: 0,
			selectAllStatus: true
		})
		if (wx.getStorageSync('selectType')) {
			type = wx.getStorageSync('selectType')
		}
		request({
			url: `goodsList`,
			token: wx.getStorageSync('token'),
			method: 'POST',
		}).then(res => {
			let data = res.data.data.type1.goodsData
			let datas = data.concat(res.data.data.type2.goodsData)
			datas.forEach(item => {
				if (item.number != 0) {
					newCar.push(item)
					allNums = allNums + item.number
				}
			})
			// console.log('总的数据', allNums)
			wx.setStorageSync("cartNumber", allNums)
			app.scanCart()
			this.setData({
				cart: newCar
			})

			if (this.data.cart.length) {
				this.selectAllDefault()
			} else {
				wx.showModal({
					title: '提示', //提示的标题,
					content: '暂无商品，去商城框框把', //提示的内容,
					showCancel: false, //是否显示取消按钮,
					confirmText: '确定', //确定按钮的文字，默认为取消，最多 4 个字符,
					confirmColor: '#3CC51F', //确定按钮的文字颜色,
					success: res => {
						if (res.confirm) {
							wx.switchTab({ url: `/pages/shopping1/shopping1` });
						}
					}
				});
			}

		})

 

	},

	//提交订单
	doSubmit() {
		let that = this
		console.log('1234567', that.data.checkCart)
		if (that.data.checkCart && that.data.checkCart.length) {
			console.log('跳转到支付页面的数据', that.data.checkCart)
			wx.navigateTo({
				url: `/pages/pay/pay?orderInfo=${JSON.stringify(that.data.checkCart)}`
			})
		} else {
			wx.showToast({
				title: '请选择商品之后再提交哦', //提示的内容,
				icon: 'none', //图标,
				duration: 1000, //延迟时间,
				mask: true, //显示透明蒙层，防止触摸穿透,
				success: res => { }
			});
		}
	},

	/** 
	 * 邮费说明
	*/
	sendRule() {
		request({
			url: `sendRule`,
			token: wx.getStorageSync('token'),
			method: 'POST',
		}).then(res => {
			this.setData({
				pre: res.data.money
			})

			console.log('邮费请求结果', res)
		})

	},
	/** 
	 * 满减活动
	*/
	activity() {
		let that = this
		let money = 0
		money = parseFloat(this.data.totalMoney)
		wx.request({
			url: app.globalData.url + 'activity',
			header: {
				'Content-Type': 'application/x-www-form-urlencoded',
				token: wx.getStorageSync('token')
			},
			method: 'POST',
			data: {
				money
			},
			success: res => {
				let totalMoney = 0
				totalMoney = parseFloat(that.data.totalMoney) - parseFloat(res.data.reduction)
				that.setData({
					totalMoney: totalMoney.toFixed(2),
					delPrice: Math.abs(res.data.reduction),
					sumMoney: parseFloat(this.data.totalMoney)
				})

			}

		})
	}

})
